<?php

namespace iBrand\Shop\Core\Repositories;

use Prettus\Repository\Eloquent\BaseRepository;
use iBrand\Shop\Core\Models\Balance;
use iBrand\Shop\Core\Models\BalanceOrder;

class BalanceOrderRepository extends BaseRepository
{
	public function model()
	{
		return BalanceOrder::class;
	}

	public function getBalanceOrderByOrderNo($order_no)
	{
		return $this->model->where('order_no', $order_no)
			->with('clerkBalance')
			->with('user')
			->with('clerkBalance.clerk')
			->with('clerkBalance.shops.city')
			->whereHas('clerkBalance', function ($query) {
				return $query;
			})->first();
	}

	public function getBalanceOrderByOrderNoClerkID($order_no, $clerk)
	{

		if ($clerk->is_clerk_owner) {
			return $this->model->where('order_no', $order_no)
				->with('clerkBalance')
				->whereHas('clerkBalance', function ($query) use ($clerk) {
					return $query->where('shop_id', $clerk->shop_id);
				})->first();
		}

		return $this->model->where('order_no', $order_no)
			->with('clerkBalance')
			->whereHas('clerkBalance', function ($query) use ($clerk) {
				return $query->where('clerk_id', $clerk->id);
			})->first();
	}

	public function getBalanceOrderByShopClerk($clerk, $limit = 10)
	{
		return $this->model->where('pay_status', 1)
			->with('clerkBalance')
			->with('clerkBalance.clerk')
			->with('clerkBalance.shops.city')
			->whereHas('clerkBalance', function ($query) use ($clerk) {
				if ($clerk->is_clerk_owner) {
					return $query->where('shop_id', $clerk->shop_id);
				} else {
					return $query->where('clerk_id', $clerk->id)->where('shop_id', $clerk->shop_id);
				}
			})->orderBy('created_at', 'desc')->paginate($limit);
	}
}